/**
 *
 */
package jp.seraph.same.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.NullArgumentException;

import jp.seraph.jsade.util.Executor;

/**
 *
 */
public abstract class AbstractViewModel implements ViewModel {
    public AbstractViewModel(String aName) {
        mChangedListeners = new ArrayList<Executor>();
        mRenamedListeners = new ArrayList<ModelRenamedEventListener>();
        mName = aName;
    }

    private List<Executor> mChangedListeners;
    private List<ModelRenamedEventListener> mRenamedListeners;
    private String mName;

    /**
     * @see jp.seraph.same.model.ViewModel#addChangedListener(jp.seraph.jsade.util.Executor)
     */
    public void addChangedListener(Executor aListener) {
        if (aListener == null)
            throw new NullArgumentException("aListener");

        mChangedListeners.add(aListener);
    }

    /**
     * @see jp.seraph.same.model.ViewModel#removeChangedListener(jp.seraph.jsade.util.Executor)
     */
    public void removeChangedListener(Executor aListener) {
        mChangedListeners.remove(aListener);
    }

    protected void fireChangedEvent() {
        for (Executor tListener : mChangedListeners) {
            tListener.execute();
        }
    }

    public void addRenamedListener(ModelRenamedEventListener aListener) {
        mRenamedListeners.add(aListener);
    }

    public void removeNameChangedListener(ModelRenamedEventListener aListener) {
        mRenamedListeners.remove(aListener);
    }

    protected void fireRenamedEvent(String aOldName, String aNewName){
        for(ModelRenamedEventListener tListener : mRenamedListeners){
            tListener.handle(this, aOldName, aNewName);
        }
    }

    public String getName() {
        return mName;
    }

    public void setName(String aNewName) {
        String tNewName = aNewName;
        String tCurrentName = this.getName();
        if(tNewName.equals(tCurrentName))
            return;

        mName = aNewName;
        fireRenamedEvent(tCurrentName, tCurrentName);
    }
}
